<template>
  <el-tabs
    v-model="data.activeTab"
    class="demo-tabs"
    @tab-click="handleClickTab"
  >
    <el-tab-pane label="对账中" name="station">
      <Table
        ref="tableStationRef"
        v-show="data.activeTab === 'station'"
        :query="data.query"
        :toolbar="data.toolbar"
        :handles="data.handles"
        @get-list="getData"
        :content="true"
      >
        <template #content>
          <el-table
            ref="table"
            :data="data.dataList"
            style="width: 100%"
            :max-height="540"
          >
            <template #empty>
              <div class="no-data-wrap">
                <div class="no-data"></div>
                <div class="text">暂无数据</div>
              </div>
            </template>
            <el-table-column
              width="60"
              type="index"
              label="序号"
              align="center"
              :index="indexMethod"
            />
            <el-table-column
              prop="type"
              label="企业身份"
              width="150"
              align="center"
              :formatter="typeFormat"
            />
            <el-table-column
              prop="operatorName"
              label="企业名称"
              width="150"
              align="center"
            >
              <template #default="scope">
                {{ scope.row.operatorName || '--' }}
              </template>
            </el-table-column>
            <el-table-column
              prop="startDate"
              label="账单开始日期"
              width="150"
              align="center"
            >
              <template #default="scope">
                {{ scope.row.startDate || '--' }}
              </template>
            </el-table-column>
            <el-table-column
              prop="endDate"
              label="账单结束日期"
              width="150"
              align="center"
            >
              <template #default="scope">
                {{ scope.row.endDate || '--' }}
              </template>
            </el-table-column>
            <el-table-column label="平台账单" align="center">
              <el-table-column
                prop="quantity"
                label="订单数"
                align="center"
                width="130"
              >
                <template #default="scope">
                  {{ scope.row.quantity == 0 ? 0 : scope.row.quantity || '--' }}
                </template>
              </el-table-column>
              <el-table-column
                prop="amount"
                label="订单金额（元）"
                align="center"
                width="130"
              >
                <template #default="scope">
                  {{ scope.row.amount || '--' }}
                </template>
              </el-table-column>
              <el-table-column
                prop="power"
                label="充电电量（度）"
                align="center"
                width="130"
              >
                <template #default="scope">
                  {{ scope.row.power || '--' }}
                </template>
              </el-table-column>
              <el-table-column
                prop="powerAmount"
                label="电费（元）"
                align="center"
                width="130"
              >
                <template #default="scope">
                  {{ scope.row.powerAmount || '--' }}
                </template>
              </el-table-column>
              <el-table-column
                prop="serviceAmount"
                label="服务费（元）"
                align="center"
                width="130"
              >
                <template #default="scope">
                  {{ scope.row.serviceAmount || '--' }}
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="互联互通方账单" align="center">
              <el-table-column
                prop="flowQuantity"
                label="订单数"
                align="center"
                width="130"
              >
                <template #default="scope">
                  {{ scope.row.flowQuantity || '--' }}
                </template>
              </el-table-column>
              <el-table-column
                prop="flowAmount"
                label="订单金额（元）"
                align="center"
                width="130"
              >
                <template #default="scope">
                  {{ scope.row.flowAmount || '--' }}
                </template>
              </el-table-column>
              <el-table-column
                prop="flowPower"
                label="充电电量（度）"
                align="center"
                width="130"
              >
                <template #default="scope">
                  {{ scope.row.flowPower || '--' }}
                </template>
              </el-table-column>
              <el-table-column
                prop="flowPowerAmount"
                label="电费（元）"
                align="center"
                width="130"
              >
                <template #default="scope">
                  {{ scope.row.flowPowerAmount || '--' }}
                </template>
              </el-table-column>
              <el-table-column
                prop="flowServiceAmount"
                label="服务费（元）"
                align="center"
                width="130"
              >
                <template #default="scope">
                  {{ scope.row.flowServiceAmount || '--' }}
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="对账结果" align="center">
              <el-table-column
                prop="resultNormalQuantity"
                label="平账订单"
                align="center"
                width="150"
              >
                <template #default="scope">
                  {{
                    scope.row.resultNormalQuantity == 0
                      ? 0
                      : scope.row.resultNormalQuantity || '--'
                  }}
                </template>
              </el-table-column>
              <el-table-column
                prop="resultDiffQuantity"
                label="数值偏差"
                align="center"
                width="150"
              >
                <template #default="scope">
                  <div
                    style="color: rgb(250, 57, 57)"
                    v-if="scope.row.resultDiffQuantity"
                  >
                    {{ scope.row.resultDiffQuantity }}
                  </div>
                  <div v-else>
                    {{ scope.row.resultDiffQuantity == 0 ? 0 : '--' }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="resultPlatformFaultQuantity"
                label="平台缺失"
                align="center"
                width="150"
              >
                <template #default="scope">
                  <div
                    style="color: rgb(250, 57, 57)"
                    v-if="scope.row.resultPlatformFaultQuantity"
                  >
                    {{ scope.row.resultPlatformFaultQuantity }}
                  </div>
                  <div v-else>
                    {{ scope.row.resultPlatformFaultQuantity == 0 ? 0 : '--' }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="resultFlowFaultQuantity"
                label="运营商缺失"
                align="center"
                width="150"
              >
                <template #default="scope">
                  <div
                    style="color: rgb(250, 57, 57)"
                    v-if="scope.row.resultFlowFaultQuantity"
                  >
                    {{ scope.row.resultFlowFaultQuantity }}
                  </div>
                  <div v-else>
                    {{ scope.row.resultFlowFaultQuantity == 0 ? 0 : '--' }}
                  </div>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column
              v-if="btnObj.list && btnObj.list.length > 0"
              label="操作"
              fixed="right"
              align="center"
              :width="btnWidth"
            >
              <template #default="scope">
                <div class="table-btn-wrap">
                  <div
                    class="table-btn"
                    v-for="(btn, index) in data.handles"
                    :key="index"
                    :style="`color: ${btn.color};`"
                    @click="btn.handle(scope.row)"
                  >
                    {{ btn.label }}
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </Table>
      <!-- 弹窗开始 -->
      <el-dialog
        v-model="data.dialogVisible"
        title="提示"
        width="430"
        class="qc-custom-dialog"
      >
        <div class="dialog-tip">
          关闭对账记录后，平台按以下对账结算金额对本次对账进行归档，是否继续？
        </div>
        <el-form ref="ruleFormRef" label-width="120px" class="dialog-form-wrap">
          <el-form-item
            label="平账账单关账依据"
            prop="closeType"
            class="has-tips"
          >
            <el-radio-group
              v-model="ruleForm.closeType"
              v-for="(item, index) in optionsS.closeTypeData"
              :key="index"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div class="tip">
              <div class="icon"></div>
              平账账单以哪方订单金额、电量作为关账结果
            </div>
          </el-form-item>
          <el-form-item label="关账金额汇总：">
            <div>
              订单金额（元）：{{
                ruleForm.closeType == 0
                  ? data.dialogData.amount
                  : data.dialogData.flowAmount
              }}
            </div>
          </el-form-item>
          <el-form-item label="">
            <div>
              电 量（度）：{{
                ruleForm.closeType == 0
                  ? data.dialogData.power
                  : data.dialogData.flowPower
              }}
            </div>
          </el-form-item>
          <el-form-item label="">
            <div>
              电 费（元）：{{
                ruleForm.closeType == 0
                  ? data.dialogData.powerAmount
                  : data.dialogData.flowPowerAmount
              }}
            </div>
          </el-form-item>
          <el-form-item label="">
            <div>
              服 务 费（元）：{{
                ruleForm.closeType == 0
                  ? data.dialogData.serviceAmount
                  : data.dialogData.flowServiceAmount
              }}
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="hide">取消</el-button>
            <el-button type="primary" v-btnAntiShake="onSubmit">
              确认
            </el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 弹窗结束 -->
    </el-tab-pane>
    <el-tab-pane label="已关闭账单" name="order">
      <Table
        v-if="data.activeTab === 'order'"
        ref="tableRef"
        :url="URL_RECONCILIATIONList"
        :columns="orderData.columns"
        :toolbar="orderData.toolbar"
        :handles="orderData.handles"
        :query="orderData.query"
        :params="{ queryType: '1' }"
      >
      </Table>
    </el-tab-pane>
  </el-tabs>
</template>
      
<script lang="ts" setup name="interconnectionReconciliationList">
import Table from '@/components/table/index.vue';
import {
  reconciliationList,
  URL_RECONCILIATIONList,
  EXPORT_RECONCILDETAILORDER,
  EXPORT_RECONCILCLOSEORDER,
  reconcilRestart,
  reconciliationClose,
  reconciliationDelete,
  getClosePreInfo,
} from '@/service/apis/financial';
import { exportFile, findKeyByValue } from '@/utils/utils';
import { queryDicByParent } from '@/service/apis/api';
import { bntAuth } from '@/utils/utils';
import { ElMessageBox } from 'element-plus';

const emit = defineEmits(['get-update']);
onActivated(() => {
  emit('get-update', (flag: boolean) => {
    if (flag) {
      tableStationRef.value?.getData();
    }
  });
});

const router = useRouter();

const tableRef = ref();
const tableStationRef = ref();
const page = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});
const btnObj = reactive({
  list: [] as any,
});
let optionsS = reactive({
  closeTypeData: [] as any,
});

optionsS.closeTypeData = [
  {
    value: 0,
    label: '平台订单',
  },
  {
    value: 1,
    label: '互联互通订单',
  },
];

const ruleForm = reactive({
  id: '',
  closeType: 0,
});

const data = reactive({
  dialogVisible: false,
  corporateIdentityData: [] as any,
  dataList: [] as any,
  detailData: {} as any,
  order: {} as any,
  todayData: {} as any,
  activeTab: 'station',
  formData: {} as any,
  dialogData: {} as any,
  type: 1,
  toolbar: [
    {
      label: '对账',
      permission: 'interconnectionReconciliationList.export',
      type: 'primary',
      plain: true,
      handle: (row: any) => {
        router.push({
          name: 'reconciliation',
        });
      },
    },
  ],
  query: [
    {
      label: '企业身份',
      prop: 'orgType',
      comName: 'select',
      props: {
        placeholder: '请选择企业身份',
        options: [] as any,
      },
    },
    {
      label: '企业名称',
      prop: 'orgName',
      comName: 'input',
      props: {
        placeholder: '请输入企业名称',
      },
    },
  ],
  handles: [
    {
      label: '争议订单明细',
      permission: 'interconnectionReconciliationList.details',
      // disabledFun: (row: any) => {
      //   return row.channelName === '清辰绿能测试企业';
      // },
      handle: (row: any) => {
        router.push({
          name: 'disputeOrderDetail',
          query: {
            id: row.id,
          },
        });
      },
    },
    {
      label: '关闭对账',
      permission: 'interconnectionReconciliationList.close',
      handle: (row: any) => {
        getClosePreInfo(row.id).then((res: any) => {
          console.log('res=====', res);
          if (res.closeAble) {
            data.dialogVisible = true;
            data.dialogData = res;
          } else {
            ElMessageBox.confirm(
              '当前对账记录有待处理争议订单，不支持关闭！',
              '提示',
              {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
              }
            ).then(() => {
              tableStationRef.value.getData();
            });
          }
        });
      },
    },
    {
      label: '删除',
      color: '#FA3939',
      permission: 'interconnectionReconciliationList.delete',
      handle: (row: any) => {
        ElMessageBox.confirm('此操作将永久删除该数据，是否继续？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          reconciliationDelete(row.id).then((res: any) => {
            tableStationRef.value.getData();
          });
        });
      },
    },
  ],
});
const orderData = reactive({
  dataList: [] as any,
  columns: [
    {
      prop: 'type',
      label: '企业身份',
      dic: [] as any,
      type: Number,
    },
    {
      prop: 'operatorName',
      label: '企业名称',
    },
    {
      prop: 'startDate',
      label: '账单开始日期',
    },
    {
      prop: 'endDate',
      label: '账单结束日期',
    },
    {
      prop: 'totalQuantity',
      label: '订单数',
      dataType: String,
    },
    {
      prop: 'resultAmount',
      label: '订单金额（元）',
    },
    {
      prop: 'resultPower',
      label: '充电电量（度）',
    },
    {
      prop: 'resultPowerAmount',
      label: '电费（元）',
    },
    {
      prop: 'resultServiceAmount',
      label: '服务费（元）',
    },

    {
      prop: 'closeTime',
      label: '订单关闭时间',
    },
    {
      prop: 'diffAmount',
      label: '对账差额',
      dataType: String,
      askContent: '对账支付金额-平台计费',
    },
  ],
  toolbar: [
    {
      label: '导出',
      permission: 'interconnectionReconciliationList.export',
      icon: 'icon-export',
      type: 'primary',
      plain: true,
      handle: (row: any) => {
        exportFile(
          EXPORT_RECONCILCLOSEORDER,
          '已关闭账单',
          tableRef.value?.getForm()
        );
      },
    },
  ],
  query: [
    {
      label: '企业身份',
      prop: 'orgType',
      comName: 'select',
      props: {
        placeholder: '请选择企业身份',
        options: [] as any,
      },
    },
    {
      label: '企业名称',
      prop: 'orgName',
      comName: 'input',
      props: {
        placeholder: '请输入企业名称',
      },
    },
    {
      label: '账单关闭时间',
      prop: 'data',
      comName: 'date',
      keys: ['closeStartDate', 'closeEndDate'],
      props: {
        type: 'daterange',
      },
    },
  ],
  handles: [
    {
      label: '重新对账',
      color: '#FA3939',
      permission: 'interconnectionReconciliationList.reverify',
      handle: (row: any) => {
        ElMessageBox.confirm(
          '对账记录重回“对账中”状态，可对冲突订单重新处理，是否继续？',
          '提示',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {
          reconcilRestart(row.id).then((res: any) => {
            tableRef.value.getData();
          });
        });
      },
    },
    {
      label: '下载对账明细',
      permission: 'interconnectionReconciliationList.download',
      handle: (row: any) => {
        console.log('导出明细---', row);
        exportFile(EXPORT_RECONCILDETAILORDER, '对账明细', {
          queryType: '-1',
          id: row.id,
        });
      },
    },
  ],
});

// 弹窗取消
const hide = () => {
  data.dialogVisible = false;
};

// 弹窗确认
const onSubmit = () => {
  data.dialogVisible = false;
  ruleForm.id = data.dialogData.id;
  console.log(ruleForm);
  reconciliationClose(ruleForm).then((res: any) => {
    tableStationRef.value.getData();
  });
};

// 企业身份字典转化
const typeFormat = (row: any, column: any) => {
  return findKeyByValue(data.corporateIdentityData, row.type);
};

// 数据切换
const handleClickTab = (e: any) => {
  console.log(e.props.name);
  if (e.props.name === 'station') {
    data.type = 1;
    tableStationRef.value?.handleQuery();
  } else {
    data.type = 0;
    tableRef.value?.handleQuery();
  }
};

// 操作栏宽度
let btnWidth = ref(30);
data.handles?.forEach((item: any, inx: number) => {
  if (bntAuth(item.permission)) {
    btnWidth.value += item.label.length * 12 + 6;
    btnObj.list.push(item);
  }
});

// 序号
const indexMethod = (index: number) => {
  return index + 1;
};

// 对账中
const getData = (page: any, search: any) => {
  const form = search.ruleForm;
  data.formData = Object.assign({ queryType: '0' }, form);
  reconciliationList(data.formData, page).then((res: any) => {
    if (res) {
      if (page.pageNo !== 1 && (!res.dataList || res.dataList?.length === 0)) {
        page.pageNo--;
        getData(page, search);
        return;
      }
      nextTick(() => {
        data.dataList = res.dataList;
        tableStationRef.value.setTable({
          total: res.totalCount,
          table: res.dataList,
        });
      });
    }
  });
};

// 已关闭账单
const getOrderData = (page: any, search: any) => {
  const form = search.ruleForm;

  data.formData = Object.assign({ queryType: '1' }, form);
  reconciliationList(data.formData, page).then((res: any) => {
    if (res) {
      nextTick(() => {
        orderData.dataList = res.dataList;
        tableRef.value.setTable({
          total: res.totalCount,
          table: res.dataList,
        });
      });
    }
  });
};

// 字典
queryDicByParent({
  listDtos: ['corporateIdentity', 'stationLimitType', 'operatorProperties'],
}).then((res: any) => {
  data.corporateIdentityData = [...res.corporateIdentity];
  // data.columns[4].dic = [...res.operatorProperties];
  data.query[0].props.options = res.corporateIdentity.filter(
    (item: any) => item.value !== '1' && item.value !== '3'
  );
  orderData.columns[0].dic = [...res.corporateIdentity];
  orderData.query[0].props.options = res.corporateIdentity.filter(
    (item: any) => item.value !== '1' && item.value !== '3'
  );
});
</script>
<style lang="scss" scoped>
@import '@/assets/styles/head.scss';

.tabs {
  display: flex;
  height: 32px;

  .tab-item {
    font-size: 13px;
    color: #5073f7;
    padding: 6px 16px;
    border: 1px solid #c4c4c4;
    border-left: 0;
    text-align: center;
    cursor: pointer;

    &:first-child {
      border-radius: 8px 0px 0px 8px;
      border-left: 1px solid #c4c4c4;
    }

    &:last-child {
      border-radius: 0px 8px 8px 0px;
    }
  }

  .active {
    background: #e5e8f6;
  }
}

.card {
  padding: 30px 0;
  margin: 20px 0;

  .card-content {
    width: 100%;

    .card-data {
      .card-item {
        display: flex;

        .title {
          margin-left: 12px;
        }

        .iconfont {
          font-size: 56px;
        }
      }
    }
  }
}

.line-card {
  margin: 0 12px;
  display: flex;
  justify-content: space-between;

  .right-card {
    width: 74%;
    height: 129px;
    background: linear-gradient(180deg, #5073f7 0%, #2e52db 100%);
    border-radius: 8px;
    padding: 10px 0;
    margin: 20px 0;
    color: #fff;

    .dividend-title {
      .title {
        font-size: 16px;
        font-weight: 500;
        text-align: center;
        margin-bottom: 10px;
      }
    }

    .charge-data {
      .charge-data-item {
        display: flex;
        justify-content: space-around;
        // text-align: center;
        // color: #262626;
        font-size: 12px;
        line-height: 20px;

        .charge-info {
          .title {
            width: 86px;
          }
        }
      }

      .charge-data-item1 {
        margin-top: 10px;
      }
    }
  }

  .left-card {
    width: 24%;
    height: 129px;
    background: linear-gradient(165.39deg, #d4dbf5 -17.51%, #a4b9ff 89.89%);
    border-radius: 8px;
    padding: 10px 0;
    margin: 20px 0;
    position: relative;

    &::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      width: 100%;
      height: 149px;
      background-image: url(@/assets/images/financial-bg.png);
      background-repeat: no-repeat;
      background-size: cover;
      opacity: 0.2;
    }

    .dividend-title {
      .title {
        font-size: 16px;
        font-weight: 500;
        text-align: center;
        margin-bottom: 10px;
        // margin-bottom: 10px;
      }
    }

    .charge-info {
      color: #262626;
      font-size: 12px;
      line-height: 20px;
      margin: 10px 0;
      text-align: center;
    }
  }

  .right-card1 {
    width: 58%;
  }

  .left-card1 {
    width: 20%;
  }
}
</style>
  